<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
    refundReasonPageService, refundReasonAddService, refundReasonByIdService,
    refundReasonUpdateService, refundReasonDeleteByIdService 
} from '@/api/order'

// 查询条件
const search = ref({})

// 原因数据列表
const tableData = ref([]);

// 表单数据
const dialogForm = ref([])

// 多选
const selectedIds = ref([])

// 分页
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(5);
// 总数
const total = ref(0);

// 表单标题
const dialogTitle = ref('')

// 表单显隐
const dialogVisible = ref(false)

onMounted(() => { 
    handleSearch()
})

// 查询
const handleSearch = async () => {
    search.value.pageSize = pageSize.value;
    const result = await refundReasonPageService(search.value)
    tableData.value = result.data.list
    total.value = parseInt(result.data.total)
}

// 获取选择列表
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
};

// 添加
const handleAdd = async () => {
    dialogTitle.value = '添加退货原因';
    dialogVisible.value = true;
    dialogForm.value = {};
}

// 处理编辑按钮点击
const handleEdit = async (id) => {
    const result = await refundReasonByIdService(id);
    dialogForm.value = result.data;
    dialogTitle.value = '编辑退货原因';
    dialogVisible.value = true;
}


// 处理开关变化
const handleSwitchChange = async (row) => {
    await refundReasonUpdateService({
        id: row.id,
        status: row.status
    })
    ElMessage.success('状态更新成功')
}


// 保存
const saveEdit = async () => {

    if(dialogForm.value.id){
        await refundReasonUpdateService(dialogForm.value);
        ElMessage.success('保存成功!');
    }else{
        // 初始化数据
        dialogForm.value.createTime = new Date()
        dialogForm.value.updateTime = new Date()
        console.log("保存数据", dialogForm.value);
        await refundReasonAddService(dialogForm.value)
        ElMessage.success('添加成功!');
    }
    
    dialogVisible.value = false;
    handleSearch()
}

// 删除
const handleDelete = async (id) => {
    // 删除
    ElMessageBox.confirm('此操作将永久删除该退货原因, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 确定删除
        await refundReasonDeleteByIdService(id);
        ElMessage.success('删除成功!');
        handleSearch();
    }).catch(() => {
        // 取消删除
        ElMessage.info('已取消删除');
    })
}

// 批量删除
const handleBatchDelete = async () => {
    ElMessageBox.confirm(
        `确认删除 ${selectedIds.value.length} 个退货原因？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
        // 反复调用删除接口
        for (let i = 0; i < selectedIds.value.length; i++) {
            await refundReasonDeleteByIdService(selectedIds.value[i])
        }
        ElMessage.success('批量删除成功!');
        selectedIds.value = [];
        handleSearch();
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
    // 同步更新 pageSize
    pageSize.value = val;
    // 同步更新搜索参数
    search.value.pageSize = val;
    console.log(`每页 ${val} 条`);
    handleSearch();
}
// 页码变化时触发
const handleCurrentChange = (val) => {
    // 同步更新 currentPage
    currentPage.value = val;
    // 同步更新搜索参数
    search.value.pageNum = val;
    console.log(`当前页: ${val}`);
    handleSearch();
}
</script>

<template>
    <div>
        <!-- 数据列表标题和添加按钮 -->
        <div class="card-header">
            <el-card shadow="never">
                <span class="card-title">退货原因数据列表</span>
                <span>
                    <el-button type="primary" size="small" @click="handleAdd">添加</el-button>
                    <el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
                </span>
            </el-card>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" class="table-list">
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <el-table-column align="center" label="编号" prop="id" width="120"></el-table-column>
            <el-table-column align="center" label="原因类型" prop="reason" width="500px"></el-table-column>
            <el-table-column align="center" label="排序" prop="sort" width="55"></el-table-column>
            <el-table-column align="center" label="是否可用" width="120">
                <template align="center" #default="scope">
                    <el-switch v-model="scope.row.status" @change="handleSwitchChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column align="center" label="添加时间" prop="createTime" width="300px"></el-table-column>
            <el-table-column align="center" label="操作">
                <template align="center" #default="scope">
                    <el-button type="primary" size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20, 30, 50, 100]" size="default" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
    <!-- 表单 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
        <el-form :model="dialogForm" label-width="100px" label-position="right">
            <el-form-item label="原因类型：" prop="reason">
                <el-input v-model="dialogForm.reason"></el-input>
            </el-form-item>
            <el-form-item label="排序：" prop="sort">
                <el-input v-model="dialogForm.sort"></el-input>
            </el-form-item>
            <el-form-item label="是否启用：">
                <el-switch v-model="dialogForm.status"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
/* card 样式 */
.card-header {
    width: 96%;
    margin: 0 0 0 2%;
}

/* card标题栏样式 */
.card-title {
    margin-right: 80%;
}   

/* 表格样式 */
.table-list {
    width: 96%;
    margin: 3vh 0 3vh 2%;
    
}

.el-pagination {
    margin: 0 0 0 25% !important;
}
</style>